#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.api import blobstore
from google.appengine.ext.webapp import util
from google.appengine.ext import db

import DataModels
class removeGarbage(webapp.RequestHandler):
    def get(self):
        galleries = DataModels.DataGallery.all().filter('deleted', True)
        
        """ Delete galleries marked to be deleted """
        for g in galleries:
            print 'Removing gallery ' + str(g.name) + '...'
            for i in g.images:
                try:
                    """ Delete image from blobstore """
                    blobstore.delete(i.blob_key.key())
                finally:
                    try:
                        """ Delete image from datastore """
                        i.delete()
                        print 'Removing image ' + str(i.name) + '...'
                    finally:
                        pass
            if g.archive_blob != None:
                """ Delete compressed gallery from blobstore """
                blobstore.delete(g.archive_blob.key())
            """ Delete gallery from database """
            g.delete()
            print 'Removed gallery ' + str(g.name) + ''
        del galleries
        """ Delete images marked to be deleted """
        images = DataModels.DataImage.all().filter('deleted', True)
        
        for i in images:
            try:
                """ Delete image from blobstore """
                blobstore.delete(i.blob_key.key())
                pass
            finally:
                try:
                    """ Delete image from datastore """
                    if i.parent().image_url == i.serving_url:
                        g = i.parent()
                        g.image_url = None
                        g.put()
                    i.delete()
                    print 'Removing image ' + str(i.name) + '...'
                finally:
                    pass

def main():
    application = webapp.WSGIApplication([
                                            ('/crons/garbage', removeGarbage)
                                         ],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()